import {
	getToken,
	setToken,
	removeToken
} from '@/util/storage'
import {
	getUserDetail
}
from '@/api/account.js';
const user = {
	state: {
		hasLogin: false,
		token: '',
		userInfo: {}
	},

	mutations: {
		SET_LOGIN: (state, payload) => {
			if (!payload.token) {
				payload.token = state.token;
			}

			state.hasLogin = true;
			state.token = payload.token;
			payload.profile.level = 1;
			state.userInfo = payload.profile;

			if (payload.token) {
				setToken(payload.token)

				// 获取用户信息
				getUserDetail(state.userInfo.userId).then(res => {
					let userInfo = res.profile;
					userInfo.level = res.level;
					state.userInfo = userInfo;
				})
			} else {
				state.userInfo.eventCount = 0;
				state.userInfo.follows = 0;
				state.userInfo.followeds = 0;
			}

		},

		REMOVE_LOGIN: (state) => {
			state.hasLogin = false;
			state.token = '';
			state.userInfo = {};

			removeToken();
		},

		SET_TOKEN: (state) => {
			state.token = getToken();
		}
	},

	actions: {
		// 获取用户信息
		saveToken({
			commit,
			state
		}, payload) {
			commit('SET_TOKEN');
		},
		saveLogin({
			commit,
			state
		}, payload) {
			commit('SET_LOGIN', payload);
		},
		// 删除用户信息
		removeLogin({
			commit,
			state
		}, payload) {
			commit('REMOVE_LOGIN');
		}


	}
};

export default user;
